package com.purong.purong.activity;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.alibaba.fastjson.JSON;
import com.purong.purong.Contant;
import com.purong.purong.R;
import com.purong.purong.adapter.BankLoanApplyMaterAdapter;
import com.purong.purong.bean.BankLoanDetBean;
import com.purong.purong.bean.BankLoanMaterItem;
import com.purong.purong.bean.BankLoanMaterialBean;
import com.purong.purong.bean.ProtocolBean;
import com.purong.purong.widget.LoadingView;
import com.purong.purong.widget.MaterChoseDialog;
import com.yao.sdk.net.ResponseInfo;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zengwenjie on 2017/11/23.
 */
public class BankLoanMaterTwoActivity extends BaseActivity {
    private RecyclerView recyclerView;
    private BankLoanApplyMaterAdapter mAdapter;
    private List<BankLoanMaterItem> itemTempList=new ArrayList<>();
//    private List<BankLoanMaterItem> itemList=new ArrayList<>();
    private BankLoanMaterialBean bean;
    private MaterChoseDialog mDialog;
    private ImageView checkImg;
    private boolean firstStep,isCheck=true;
    private BankLoanDetBean detBean;
    private String applyMoney,applyPeriod,loanApplyId;
    private LoadingView loadingView;
    @Override
    public int getRootViewId() {
        return R.layout.activity_apply_material_two;
    }

    @Override
    public void initBundle() {
        detBean=(BankLoanDetBean)getIntent().getSerializableExtra("BANK_LOAN");
        applyMoney=getIntent().getStringExtra("APPLY_MONEY");
        applyPeriod=getIntent().getStringExtra("APPLY_PERIOD");
        firstStep=getIntent().getBooleanExtra("FIRST_STEPS",false);
        loanApplyId=getIntent().getStringExtra("APPLY_ID");
    }

    @Override
    public void initView() {
        if (!firstStep)
            findViewById(R.id.agreement_lay).setVisibility(View.VISIBLE);
        loadingView=(LoadingView)findViewById(R.id.loading_view);
        loadingView.setLoadListener(new LoadingView.OnLoadListener() {
            @Override
            public void onReload() {
                getMaterial();
            }

            @Override
            public void onRefresh() {

            }
        });
        checkImg=(ImageView)findViewById(R.id.check_img);
        recyclerView=(RecyclerView)findViewById(R.id.recycler_view);
        mAdapter=new BankLoanApplyMaterAdapter(this);
        mAdapter.setData(itemTempList);
        mAdapter.setOnMaterCliclListener(new BankLoanApplyMaterAdapter.OnMaterCliclListener() {
            @Override
            public void onItemClick(int position, int type, BankLoanMaterItem item) {
                if (mDialog==null)
                    initDialog();
                if (item.getType()!= BankLoanMaterItem.TYPE_THREE&&item.getType()!= BankLoanMaterItem.TYPE_FOUR
                        &&item.getChild()!=null&&item.getChild().size()!=0){
                    mDialog.setData(item.getChild());
                    mDialog.show();
                }

            }
        });
        recyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
        recyclerView.setAdapter(mAdapter);
        initDialog();
    }
    private void getProtocol(){
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("protocol_code","LoanProtocol");
        request(Contant.PROTOCOL, params, true,true);
    }
    private void getMaterial(){
        loadingView.loading();
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("material_group_id",detBean.getMaterial_group_id());
        if (!request(Contant.LOAN_MATERIAL, params, true, false)){
            loadingView.fail();
        }
    }
    private void setMaterial(String material){
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("material",material);
        request(Contant.LOAN_APPLY_MATERIAL, params, true, true);
    }
    private void initDialog(){
        mDialog=new MaterChoseDialog(this);
        mDialog.setOnMaterChoseListener(new MaterChoseDialog.OnMaterChoseListener() {
            @Override
            public void onChose(int position, BankLoanMaterItem item) {
                updataItemList(item);
            }
        });
    }
    @Override
    public void initData() {
        if (detBean==null)
            return;
        getMaterial();
    }
    private  List<BankLoanMaterItem> childList=new ArrayList<>();
    private void getAllChild(BankLoanMaterItem item){
        if (item.getChild()!=null&&item.getChild().size()!=0){
            childList.addAll(item.getChild());
            for (int i = 0; i <item.getChild().size() ; i++) {
                getAllChild(item.getChild().get(i));
            }
        }
    }
    private void deleteItem(String id){
        for (int j = itemTempList.size()-1; j >=0 ; j--) {
            if (itemTempList.get(j).getParent_id().equals(id)){
                childList.clear();
                childList.add(itemTempList.get(j));
                getAllChild(itemTempList.get(j));

                for(int k=0;k<childList.size();k++){
                    childList.get(k).setChose_chlid_name("请选择");
                    childList.get(k).setChose_chlid_id("-1");
                    childList.get(k).setInput_content("");
                }
                itemTempList.removeAll(childList);

            }
        }
    }
    private void updataItemList(BankLoanMaterItem item){
        String parentId=item.getParent_id();
        for (int i = 0; i <itemTempList.size() ; i++) {
            if (itemTempList.get(i).getMaterial_item_id().equals(parentId)){
                deleteItem(itemTempList.get(i).getChose_chlid_id());
                break;
            }
        }
//        findViewById(R.id.center_title).setFocusable(true);
        for (int i = 0; i <itemTempList.size() ; i++) {
            if (itemTempList.get(i).getMaterial_item_id().equals(parentId)){
                itemTempList.get(i).setChose_chlid_name(item.getMaterial_item_name());
                itemTempList.get(i).setChose_chlid_id(item.getMaterial_item_id());
                itemTempList.addAll(i+1,item.getChild());
                break;
            }
        }
        mAdapter.notifyDataSetChanged();

    }
    private void initItemList(List<BankLoanMaterItem> list){
        if (list!=null&&list.size()!=0){
            for (int i = 0; i <list.size() ; i++) {
                if ((list.get(i).getChild()==null||list.get(i).getChild().size()==0)&&
                        list.get(i).getMaterial_item_unit()!=null&&!list.get(i).getMaterial_item_unit().equals("")){
                    if (list.get(i).getLevel().equals("1")){
                        list.get(i).setType(BankLoanMaterItem.TYPE_FOUR);
                    }else {
                        list.get(i).setType(BankLoanMaterItem.TYPE_THREE);
                    }

                }else if (list.get(i).getLevel().equals("1")){
                    list.get(i).setType(BankLoanMaterItem.TYPE_ONE);
                }else {
                    list.get(i).setType(BankLoanMaterItem.TYPE_TWO);
                }
                if (list.get(i).getChild()!=null&&list.get(i).getChild().size()!=0){
                    initItemList(list.get(i).getChild());
                }
            }
        }
    }
    private String getMateria(){
        if (itemTempList==null)
            return null;
        StringBuffer buffer=new StringBuffer();
        for (int i = 0; i <itemTempList.size() ; i++) {
            if (itemTempList.get(i).getType()== BankLoanMaterItem.TYPE_THREE||itemTempList.get(i).getType()== BankLoanMaterItem.TYPE_FOUR){
                if (itemTempList.get(i).getInput_content().equals("")){
                    showToast("请输入"+itemTempList.get(i).getMaterial_item_name());
                    return null;
                }else {
                    buffer.append(itemTempList.get(i).getMaterial_item_id()+"="+itemTempList.get(i).getInput_content());
                    buffer.append("{|}");
                    continue;
                }

            }else {
                if (itemTempList.get(i).getChose_chlid_id().equals("-1")){
                    showToast("请选择"+itemTempList.get(i).getMaterial_item_name());
                    return null;
                }else {
                    buffer.append(itemTempList.get(i).getMaterial_item_id()+"="+itemTempList.get(i).getChose_chlid_name());
                    buffer.append("{|}");
                    continue;
                }

            }
        }
        String result=buffer.toString();
        if (result.equals("")){
            return result;
        }else {
            return result.substring(0,result.length()-3);
        }
    }
    private void setData(){
        initItemList(bean.getBank_list());
        itemTempList.clear();
//        itemList.clear();
//        itemList.addAll(bean.getBank_list());
        itemTempList.addAll(bean.getBank_list());
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onResponse(ResponseInfo responseInfo) {
        if (hasDestroy())
            return;
        super.onResponse(responseInfo);
        if (responseInfo.url.equals(Contant.LOAN_MATERIAL)){
            if (responseInfo.isRequestOk){
                try{
                    bean= JSON.parseObject(responseInfo.content,BankLoanMaterialBean.class);
                    if (bean!=null&&bean.getBank_list()!=null)
                    setData();
                    loadingView.finish();
                    Log.e("zwj",bean.toString());
                }catch (Exception e){
                    loadingView.fail();
                }
            }else {
                loadingView.fail();
            }
        }else if (responseInfo.url.equals(Contant.PROTOCOL)){
            if (responseInfo.isRequestOk){
                try {
                    ProtocolBean bean= JSON.parseObject(responseInfo.content,ProtocolBean.class);
                    if (bean!=null&&bean.getUrl()!=null){
                        Intent intent=new Intent(this,WebActivity.class);
                        intent.putExtra("TITLE", "普融服务协议");
                        intent.putExtra("URL", bean.getUrl());
                        intent.putExtra("TITLEBAR", true);
                        startActivity(intent);
                    }

                }catch (Exception e){

                }
            }
        }else if (responseInfo.url.equals(Contant.LOAN_APPLY_MATERIAL)){
            Log.e("zwj",responseInfo.content);
            if (responseInfo.isRequestOk){
                try{
                    if (detBean!=null&&applyMoney!=null&&applyPeriod!=null){
                        Intent intent=new Intent(this,BankLoanResultActivity.class);
                        intent.putExtra("BANK_LOAN",detBean);
                        intent.putExtra("APPLY_MONEY",applyMoney);
                        intent.putExtra("APPLY_PERIOD",applyPeriod);
                        intent.putExtra("APPLY_ID",loanApplyId);
                        startActivity(intent);
                    }
                    this.finish();

                }catch (Exception e){

                }
            }
        }
    }

    public void onClick(View v){
        switch (v.getId()){
            case R.id.protocol:
                getProtocol();

                break;
            case R.id.check_img:
                if (!isCheck){
                    checkImg.setImageResource(R.drawable.icon_checkbox_sel);
                    isCheck=true;
                }else {
                    checkImg.setImageResource(R.drawable.icon_checkbox_nor);
                    isCheck=false;
                }
                break;
            case R.id.next:
                if (!firstStep&&!isCheck){
                    showToast("未同意普融服务协议");
                    return;
                }
                String result=getMateria();
                if (result!=null){
                    setMaterial(result);
                }else {
                    Log.e("zwj","...result=null");
                }
                break;
            case R.id.left_back:
                this.finish();
                break;
        }
    }
}
